package handler

import (
	"code-master/cache"
	"code-master/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")

	data := models.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
		"data": data,
	})
	return
}
func Del(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	err := models.DB.Where("id = ?", id).Delete(&models.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var user []models.Article
	redis_list_key := "list_key"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		models.DB.Model(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(result), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return

}
